package com.cx.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author flysand
 * @package com.cx.common.util
 * @date 2021-11-18 01:13
 * @des CamelCaseUtils:驼峰转换工具类
 */
public class CamelCaseUtils {

    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");


    private static final Pattern LINE_PTTERN = Pattern.compile("_(\\w)");


    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = LINE_PTTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线
     *
     * @param str 驼峰字符串
     * @return 下划线字符串
     */
    public static String humpToLine(String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
